import axios from 'axios'
import { getToken } from './auth'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = getToken()
    if (token) {
      config.headers.Authorization = token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    if (response.data.code !== 10000) {
      Message.error(response.data.msg)
      return Promise.reject(response.data)
    } else {
      return response.data
    }
  },
  error => {
    // 错误类型有可能有好多种 根据不同的错误码做不同的用户提示 写的位置都在这里
    console.log('接口请求报错', error.response)
    if (error.response && error.response.status === 401) {
      store.commit('user/clearUserInfo')
      router.push('/login')
    }
    Message({
      type: 'warning',
      message: error.response && error.response.data.msg || '请求失败，请稍后再试'
    })
    return Promise.reject(error)
  }
)

export default service
